# -*- coding: UTF-8 -*-
import copy
import inspect
from functools import wraps

from flask import request, make_response, jsonify

from core.form.base import BaseForm
from core.utils import underline_variable


def params(form: BaseForm):
    def decorate(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            form.process(data=dict(request.args))
            parameter = inspect.signature(func)
            parameters = dict(parameter.parameters)
            _underline_variable = underline_variable(form.__class__.__name__)
            if _underline_variable in parameters.keys():
                kwargs.update({_underline_variable: copy.deepcopy(form)})
            if form.validate() is False:
                return make_response(jsonify(form.errors_dto()), 400)
            return func(*args, **kwargs)

        return wrapper

    return decorate


def payload(form: BaseForm):
    def decorate(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            form.process(data=request.get_json())
            parameter = inspect.signature(func)
            parameters = dict(parameter.parameters)
            _underline_variable = underline_variable(form.__class__.__name__)
            if _underline_variable in parameters.keys():
                kwargs.update({_underline_variable: copy.deepcopy(form)})
            if form.validate() is False:
                return make_response(jsonify(form.errors_dto()), 400)
            return func(*args, **kwargs)

        return wrapper

    return decorate
